package goTool

import (
	"code.google.com/p/graphics-go/graphics"
	"image"
	"image/jpeg"
	"image/png"
	"log"
	"os"
	"path"
)

type Zimage struct {
	src   string
	dst   string
	scale int
}

// sourcePath: source file path
// dstPath: distribute file path
// scale: Scaling
// author: zhaoce
// date: 2018-03-16

func (l *Zimage) Thubmail() error {
	src, err := loadImage(l.src)
	if err != nil {
		log.Fatal(err)
	}

	extImage := getFileExt(l.src)
	srcBounds := src.Bounds().Max.Div(3)
	dst := image.NewRGBA(image.Rect(0, 0, srcBounds.X, srcBounds.Y))

	err = graphics.Thumbnail(dst, src)
	if err != nil {
		log.Fatal(err)
	}

	return saveImage(l.dst, extImage, dst)
}

// Read source image
// author: zhaoce
// date: 2018-03-16

func loadImage(src string) (img image.Image, err error) {
	f, err := os.Open(src)
	if err != nil {
		return
	}
	defer f.Close()
	img, _, err = image.Decode(f)
	return
}

//Save Thumbnail image
// author: zhaoce
// date: 2018-03-16
func saveImage(dst, ext string, img image.Image) error {
	dstImage, _ := os.Create(dst + "." + ext)
	defer dstImage.Close()

	switch ext {
	case "png":
		return png.Encode(dstImage, img)
	case "jpeg":
		return jpeg.Encode(dstImage, img, &jpeg.Options{99})
	default:
	}
	return nil
}

/**
 * Get filename Suffix
 * @author: zhaoce
 * @date: 2018-03-16
 */
func getFileExt(filename string) string {
	filePathWithSuffix := path.Base(filename)
	return path.Ext(filePathWithSuffix)[1:]
}
